package com.app.megaprosoft.modyimcarcare;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

import com.app.megaprosoft.DB.Ar;
import com.app.megaprosoft.DB.FFUser;
import com.app.megaprosoft.DB.SQLiteDBClass;
import com.app.megaprosoft.DB.UserGroup;
import com.megaprosoft.modyimcarcare.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class Carcare_Login extends Activity {
	
	public static final int 	DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog 		mProgressDialog;
	private Animation 			shake;
	private AlertDialog 		loginDialog;
	
	private String 				Data_user[][],Data_company[][];
	private Boolean 			ck_login = false;
	
	private String   			FFUserOID
								,UserName
								,Password
								,DepCode
								,DepName
								,UserGroupOID
								,UserGroupName
								,UserGroupCode
								,PicPath
								,user_Password;
	
	private TextView 			tv_company,tv_Password;
	private Button button_1,button_2,button_3,button_4,button_5,
					button_6,button_7,button_8,button_9,button_0,button_clrsr,button_cancle,button_enter;
	
	Intent Main;
	UserGroup usergroup = new UserGroup();
	FFUser ffuser = new FFUser();
	Carcare_SessionManagement session;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_carcare_activity_login);
		setTitle("ศูนย์เอาใจใส่รถยนต์มดขยัน");
		
		// Session Manager
        session = new Carcare_SessionManagement(getApplicationContext());   
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
        
		ffuser.setContext(getApplicationContext());
		usergroup.setContext(getApplicationContext());
		
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		
		tv_company = (TextView) findViewById(R.id.a_login_company);
		
		Main = new Intent(Carcare_Login.this,Carcare_Main.class);
		
		LayoutInflater inflater = Carcare_Login.this.getLayoutInflater();
		
        loginDialog = new AlertDialog.Builder(Carcare_Login.this)
        .setView(inflater.inflate(R.layout.a_carcare_dialog_confirmuser, null))
        .setCancelable(false)
        .create();
        
        loginDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
				
				tv_Password = (TextView) loginDialog.findViewById(R.id.a_login_password);
				tv_Password.setText("");
				
				button_0 = (Button) loginDialog.findViewById(R.id.a_login_button0);
				button_0.setOnClickListener(text_0);
				button_1 = (Button) loginDialog.findViewById(R.id.a_login_button1);
				button_1.setOnClickListener(text_1);
				button_2 = (Button) loginDialog.findViewById(R.id.a_login_button2);
				button_2.setOnClickListener(text_2);
				button_3 = (Button) loginDialog.findViewById(R.id.a_login_button3);
				button_3.setOnClickListener(text_3);
				button_4 = (Button) loginDialog.findViewById(R.id.a_login_button4);
				button_4.setOnClickListener(text_4);
				button_5 = (Button) loginDialog.findViewById(R.id.a_login_button5);
				button_5.setOnClickListener(text_5);
				button_6 = (Button) loginDialog.findViewById(R.id.a_login_button6);
				button_6.setOnClickListener(text_6);
				button_7 = (Button) loginDialog.findViewById(R.id.a_login_button7);
				button_7.setOnClickListener(text_7);
				button_8 = (Button) loginDialog.findViewById(R.id.a_login_button8);
				button_8.setOnClickListener(text_8);
				button_9 = (Button) loginDialog.findViewById(R.id.a_login_button9);
				button_9.setOnClickListener(text_9);
				button_clrsr = (Button) loginDialog.findViewById(R.id.a_login_button_clrscr);
				button_clrsr.setOnClickListener(text_clrsr);
				button_enter = (Button) loginDialog.findViewById(R.id.a_login_button_enter);
				button_enter.setOnClickListener(text_enter);
				button_cancle = (Button) loginDialog.findViewById(R.id.a_login_button_cancle);
				button_cancle.setOnClickListener(text_cancle);
				
			}
		});
        Define_ArGroup();
        
	}
	
	public void Define_User(){
		try {
			
			Data_user = ffuser.SelectAll_user(UserGroupOID);
			
			 final ListView lv = (ListView) findViewById(R.id.carcare_login_listuser);
		        lv.setAdapter(new User_Adapter(this,Data_user));
		        // OnClick
		        lv.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
						try{
							FFUserOID  		= Data_user[position][0].toString(); 
							UserName 		= Data_user[position][2].toString(); 
							Password 		= Data_user[position][3].toString(); 
							DepCode 		= Data_user[position][4].toString(); 
							DepName  		= Data_user[position][5].toString(); 
							UserGroupName 	= Data_user[position][7].toString(); 
							PicPath  		= Data_user[position][8].toString(); 
							loginDialog.show();
//							 Toast.makeText(getApplicationContext(),
//										"Go: " + Data_user[position][3].toString(), Toast.LENGTH_SHORT).show();
						}catch(Exception e){
//							 Toast.makeText(getApplicationContext(),
//										"ERROR: " + Data_user[position][8].toString(), Toast.LENGTH_SHORT).show();
						}
					}
				});
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}   
       
	}
	
	public class User_Adapter extends BaseAdapter 
    {
        private Context context;
        private String[][] lis;
        
        public User_Adapter(Context c, String[][] li) 
        {
        	// TODO Auto-generated method stub
            context = c;
            lis = li;
        }
        
        public int getCount() {
        	// TODO Auto-generated method stub
        	try{
        		 return lis.length;
			}catch(Exception e){
				return 0;
			}
           
        }
 
        public Object getItem(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
 
        public long getItemId(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
 
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_user, null); 
			}
					
			// ColPhoto
//			String strPath = "/mnt/sdcard/contact/"+lis[position][3].toString();
//			ImageView imgPhoto = (ImageView) convertView.findViewById(R.id.ColPhoto);
//			imgPhoto.setPadding(5, 5, 5, 5);
//			Bitmap bm = BitmapFactory.decodeFile(strPath);
////			Bitmap bm = BitmapFactory.decodeResource(R.drawable.carcare_logo);
//			int width=100;
//		    int height=100;
//		    Bitmap resizedbitmap = Bitmap.createScaledBitmap(bm, width, height, true);
//		    imgPhoto.setImageBitmap(resizedbitmap);
			
			// ColName
			TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
			txtName.setPadding(0, 0, 0, 0);
			txtName.setText(lis[position][2].toString());
			
			// ColEmail
			TextView txtEmail = (TextView) convertView.findViewById(R.id.Coldep);
			txtEmail.setPadding(0, 0, 0, 0);
			txtEmail.setText(lis[position][5].toString());
			return convertView;
		}
    } 
	
	public void Define_ArGroup(){
		try {
			Data_company = usergroup.selectAll_FFUserGroup();
			final GridView lv = (GridView)findViewById(R.id.carcare_login_company);
	       	
	        lv.setAdapter(new Company_Adapter(this,Data_company));
	        lv.setClickable(true);
	        lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
					UserGroupOID   = Data_company[position][0].toString();
					UserGroupCode	= Data_company[position][1].toString();
					UserGroupName 	= Data_company[position][2].toString();
					tv_company.setText(UserGroupName);
					try{
						Define_User();
					}catch(Exception e){
						
					}
				}
			});
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}   
	
        }
	
	 public class Company_Adapter extends BaseAdapter 
	    {
	        private Context context;
	        private String[][] lis;
	        
	        public Company_Adapter(Context c, String[][] li) 
	        {
	        	// TODO Auto-generated method stub
	            context = c;
	            lis = li;
	        }
	 
	        public int getCount() {
	        	// TODO Auto-generated method stub
	        	try{
	        		 return lis.length;
				}catch(Exception e){
					return 0;
				}
	        }
	 
	        public Object getItem(int position) {
	        	// TODO Auto-generated method stub
	            return position;
	        }
	 
	        public long getItemId(int position) {
	        	// TODO Auto-generated method stub
	            return position;
	        }
	 
			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 
				if (convertView == null) {
					convertView = inflater.inflate(R.layout.list_company, null); 
				}
						
				// ColPhoto
//				String strPath = "/mnt/sdcard/contact/"+lis[position][3].toString();
//				ImageView imgPhoto = (ImageView) convertView.findViewById(R.id.ColPhoto);
//				imgPhoto.setPadding(5, 5, 5, 5);
//				Bitmap bm = BitmapFactory.decodeFile(strPath);
////				Bitmap bm = BitmapFactory.decodeResource(R.drawable.carcare_logo);
//				int width=100;
//			    int height=100;
//			    Bitmap resizedbitmap = Bitmap.createScaledBitmap(bm, width, height, true);
//			    imgPhoto.setImageBitmap(resizedbitmap);
				
				// ColName
				TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
				txtName.setPadding(0, 0, 0, 0);
				txtName.setText(lis[position][2].toString());
				
				return convertView;
			}
	    } 
	 
	private OnClickListener text_clrsr = new OnClickListener() {
        public void onClick(View v) {
        	tv_Password.setText("");
        }
    };
    private OnClickListener text_0 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"0");
        }
    };
    private OnClickListener text_1 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"1");
        }
    };
    private OnClickListener text_2 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"2");
        }
    };
    private OnClickListener text_3 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"3");
        }
    };
    private OnClickListener text_4 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"4");
        }
    };
    private OnClickListener text_5 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"5");
        }
    };
    private OnClickListener text_6 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"6");
        }
    };
    private OnClickListener text_7 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"7");
        }
    };
    private OnClickListener text_8 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"8");
        }
    };
    private OnClickListener text_9 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_Password.getText().toString();
        	tv_Password.setText(tmp+"9");
        }
    };
    private OnClickListener text_cancle = new OnClickListener() {
        public void onClick(View v) {
        	loginDialog.dismiss();
        }
    };
    private OnClickListener text_enter = new OnClickListener() {
        public void onClick(View v) {
        	user_Password = tv_Password.getText().toString();
        	new  LoadingLogin().execute();
        }
    };
    

	 @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case DIALOG_DOWNLOAD_PROGRESS:
	            mProgressDialog = new ProgressDialog(this);
	            mProgressDialog.setMessage("Checking.....");
	            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	            mProgressDialog.setCancelable(true);
	            mProgressDialog.show();
	            return mProgressDialog;
	        default:
	            return null;
	        }
	    }
	 	//-----------AsyncTask-Loading----------------------------------//
	    public class LoadingLogin extends AsyncTask<String, Void, Void> {
	        @SuppressWarnings("deprecation")
			protected void onPreExecute() {
	        	super.onPreExecute();
	        }
	        
			@Override
	        protected Void doInBackground(String... params) {
				
	        	try{
	        		if(user_Password.equals(Password)){
	        			ck_login=true;
	        		}else{
	        			ck_login=false;
	        		}
	        	}catch(Exception e){
	        		ck_login=false;
	        	}
	    		return null;
	        }

	        @SuppressWarnings("deprecation")
			protected void onPostExecute(Void unused) {
	        	
	        	if(ck_login==true){
	 	          session.createLoginSession(
	 	        		  FFUserOID,
	 	        		  UserName, 
	 	        		  DepCode, 
	 	        		  DepName, 
	 	        		  UserGroupOID, 
	 	        		  UserGroupName, 
	 	        		  "A"+UserGroupCode,
	 	        		  PicPath, 
	 	        		  "L01", 
	 	        		  "CarcareTablet01");
	 			   startActivity(Main);
	 		       finish();
	        	}else{
	        		tv_Password.startAnimation(shake);
	        		tv_Password.setText("");
	        	}
	        } 
	    }
	    
	 
	 @Override
		public void onBackPressed() {
		  
		        new AlertDialog.Builder(this)
		        .setTitle("ออกจากโปรแกรม")
		        .setIcon(R.drawable.erroralert)
		        .setMessage("ต้องการออกจากโปรแกรม")
		                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                        finish();
		                        System.exit(0);
		                    }
		                })
		                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
//		                    	loginDialog.show();
//		                    	System.exit(0);
		                    }
		                }).create().show();
		}


	
}
